<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\OperationLogs;
use App\Model\Permissions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Permission;

class PermissionController extends BaseController
{
    public function __construct(Request $request, Permissions $permissions)
    {
        parent::__construct($request);
        $this->model = $permissions;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->getList($request));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Support\MessageBag
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required|unique:mysql.permissions,name|max:50'
        ],[
            'required' => '权限名不可为空',
            'unique' => '权限名已存在',
            'max' => '权限名不可超过50个字符'
        ]);
        if($validator->fails()){
            return $this->toJson(self::PARAM_ERROR, [],$validator->errors()->all()[0]);
        }
        $res = Permission::create($request->only(['name','desc','pid']));

        OperationLogs::createData($request, OperationLogs::PERMISSION,'新增权限');
        return $this->toJson(self::SUCCESS,$res);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $res = Permission::getPermissions(['role_id' => $id]);
        return $this->toJson(self::SUCCESS,$res);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required|max:50'
        ],[
            'required' => '权限名不可为空',
            'max' => '权限名不可超过50个字符'
        ]);
        if($validator->fails()){
            return $this->toJson(self::PARAM_ERROR,[], $validator->errors()->all()[0]);
        }
        $res = Permissions::where(['id' => $id])->update($request->only(['name','desc','pid']));

        OperationLogs::createData($request,OperationLogs::PERMISSION, '编辑权限', $id);
        return $this->toJson(self::SUCCESS,$res);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request,$id)
    {
        // 先判断是否有子级
        if(Permission::where(['pid' => $id])->count() > 0){
            return $this->toJson( self::PARAM_ERROR, [],'请先删除子类 ');
        }
        Permission::destroy($id);
        OperationLogs::createData($request, OperationLogs::PERMISSION,'删除权限', $id);
        return $this->toJson();
    }

    public function list(){
        $permissions = Permission::all();
        $group = $permissions->groupBy('pid');
        $parents = $group->shift();

        $children = [];
        foreach ($group->flatten()->toArray() as $item) {
            $children[$item['pid']][] = [
                'id' => $item['id'],
                'label' => $item['desc']
            ];
        }
        $permissionsTree = [];
        if(!$parents) return $this->toJson(self::SUCCESS);
        foreach ($parents->toArray() as $parent) {
            $permissionsTree[] = [
                'id' => $parent['id'],
                'label' => $parent['desc'],
                'children' => $children[$parent['id']] ?? []
            ];
        }

        return $this->toJson(self::SUCCESS,$permissionsTree);
    }

    /**
     * pid 为 0 的权限
     * @return \Illuminate\Http\JsonResponse
     */
    public function parents(){
        $res = Permission::where(['pid' => 0])->get(['id', 'desc']);
        return $this->toJson(self::SUCCESS,$res);
    }

    public function getPermission($id) {
        return $this->toJson(self::SUCCESS, $this->model->getPermissionById($id));
    }
}
